import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Description
 * @author Jerry
 * @date 2016-08-08
 */
public class UploadServlet extends HttpServlet{
    private static final long serialVersionUID = 4751765612776440272L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        uploadFileByOutPutStream(resp);
    }

    private void uploadFileByOutPutStream(HttpServletResponse response) throws IOException {
     //   String realPath = this.getServletContext().getRealPath("/image/photo1.jpg");
        String realPath = this.getServletContext().getRealPath("/一张神奇的图片.jpg");
        String fileName =realPath.substring(realPath.lastIndexOf("\\")+1);
        response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
        InputStream in = new FileInputStream(realPath);
        int len = 0;
        byte[] buffer = new byte[1024];
        OutputStream out = response.getOutputStream();
        while((len = in.read(buffer))>0){
            out.write(buffer,0,len);
        }
       in.close();
        out.close();


    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPut(req, resp);
    }
}
